<template>
  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :width="formType === 'create' ? '50%' : '80%'"
  >
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
    >
      <el-row :gutter="20">
        <!--        <el-col :span="formType === 'create' ? 24 : 12">-->
        <el-col :span="24">
          <el-row>
            <el-col v-if="formType === 'update'" :span="24">
              <el-form-item label="发布人">
                <el-avatar :src="formData?.userInfo?.avatar" />
                <span class="m-l"> {{ formData?.userInfo?.nickname }} </span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="动态标题" prop="title">
                <el-input v-model="formData.title" placeholder="请输入动态标题" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="动态话题" prop="tagId">
                <el-select v-model="formData.tagId" placeholder="请选择">
                  <el-option
                    v-for="item in topicList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="动态封面" prop="url">
                <el-popover placement="right" :width="300" trigger="hover">
                  <template #reference>
                    <UploadImg v-model="formData.url" height="150px" />
                  </template>
                  <el-input
                    v-model="formData.url"
                    :rows="3"
                    type="textarea"
                    placeholder="可直接输入图片网络链接地址"
                  />
                </el-popover>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input-number
                  v-model="formData.sort"
                  :min="0"
                  clearable
                  controls-position="right"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="浏览量" prop="browsCount">
                <el-input-number
                  v-model="formData.browsCount"
                  :min="0"
                  clearable
                  controls-position="right"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="点赞量" prop="thumbCount">
                <el-input-number
                  v-model="formData.thumbCount"
                  :min="0"
                  clearable
                  controls-position="right"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="动态配图" prop="sliderPicUrls">
                <UploadImgs v-model="formData.sliderPicUrls" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="动态内容">
                <el-input
                  v-model="formData.content"
                  :rows="5"
                  type="textarea"
                  placeholder="请输入..."
                />
                <!--            <Editor v-model="formData.teachContent" height="350px" />-->
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
<!--        <el-col :span="12">-->
<!--          &lt;!&ndash; 分页 &ndash;&gt;-->
<!--          <Pagination-->
<!--            v-model:limit="queryParams.pageSize"-->
<!--            v-model:page="queryParams.pageNo"-->
<!--            :total="totalComment"-->
<!--            @pagination="getCommentList"-->
<!--          />-->
<!--        </el-col>-->
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确定修改</el-button>
      <el-button
        v-if="formData.status == 0"
        :disabled="formLoading"
        type="primary"
        @click="handleAccess"
        >审核发布
      </el-button>
      <el-button
        v-if="formData.status == 0"
        :disabled="formLoading"
        type="danger"
        @click="handleDeny"
        >驳回发布
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <!--  <SpuSelect ref="spuSelectRef" @confirm="selectSpu" />-->
</template>
<script lang="ts" setup>
import { DICT_TYPE, getBoolDictOptions, getIntDictOptions } from '@/utils/dict'
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as ClubApi from '@/api/club/dynamic'
import * as topicApi from '@/api/club/topic'

import { UploadImg } from '@/components/UploadFile'
import { getDynamicCommentList } from '@/api/club/dynamic'

defineOptions({ name: 'TeachForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const totalComment = ref(0) // 列表的总页数
const commentList = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  categoryId: undefined,
  dynamicId: undefined,
  createTime: []
})

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('新增/编辑') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  teachType: undefined,
  title: undefined,
  author: undefined,
  url: undefined,
  introduction: undefined,
  sliderPicUrls: [], // 数组形式配图
  sourceUrl: '', // 字符串形式配图
  sort: 0,
  status: undefined
})
const formRules = reactive({
  teachType: [{ required: true, message: '分类id不能为空', trigger: 'blur' }],
  title: [{ required: true, message: '动态标题不能为空', trigger: 'blur' }],
  url: [{ required: true, message: '动态封面图片地址不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  spuId: [{ required: true, message: '商品关联id不能为空', trigger: 'blur' }],
  deviceId: [{ required: true, message: '商品关联id不能为空', trigger: 'blur' }],
  recommendHot: [{ required: true, message: '是否热门(小程序)不能为空', trigger: 'blur' }],
  recommendBanner: [{ required: true, message: '是否轮播图(小程序)不能为空', trigger: 'blur' }],
  teachContent: [{ required: true, message: '动态内容不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const spuSelectRef = ref() // 商品和属性选择 Ref
const selectSpu = async (spuId: number, skuIds: number[], spu: any) => {
  formData.value.spuId = spuId
  formData.value.deviceId = spuId
  formData.value.deviceName = spu.name // 赋值商品名称
  formData.value.deviceTypeId = spu.categoryId // 赋值商品分类ID
  //   重新获取产品信息用于回显
  const spuDatas = await getSpuList(spuId)
  spuList.value = spuDatas
}
const spuList = ref<ProductSpuApi.Spu[]>([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type) || '新增/编辑'
  formType.value = type
  resetForm()
  // 修改时，设置数据
  formData.value.teachVideo = ''
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ClubApi.getDynamic(id)
      //   将字符串动态配图转换为数组sliderPicUrls
      formData.value.sliderPicUrls = formData.value.sourceUrl.split(',')
      // await getCommentList() // 获取动态评论列表
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  //   将数组动态配图sliderPicUrls转换为字符串sourceUrl
  formData.value.sourceUrl = formData.value.sliderPicUrls.join(',')
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await ClubApi.createDynamic(data)
      message.success(t('common.createSuccess'))
    } else {
      await ClubApi.updateDynamic(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    teachType: undefined,
    title: undefined,
    author: undefined,
    url: undefined,
    introduction: undefined,
    sliderPicUrls: [], // 数组形式配图
    sourceUrl: '', // 字符串形式配图
    sort: 0,
    status: undefined,
    spuId: 0,
    deviceId: 0
  }
  formRef.value?.resetFields()
}
/** 审核通过按钮操作 */
const handleAccess = async (id: number) => {
  ElMessageBox.confirm('确认通过该社区发布内容吗?', '通过社区发布', {
    confirmButtonText: '确认通过',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let data = {
        id: formData.value.id,
        status: '10' // 默认10已通过
      }
      await ClubApi.auditDynamic(data)
      ElMessage({
        type: 'success',
        message: '通过成功'
      })
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    })
    .catch(() => {})
}
/** 驳回按钮操作 */
const handleDeny = async (id: number) => {
  ElMessageBox.confirm('确认驳回该社区发布内容吗?', '驳回社区发布', {
    confirmButtonText: '确认驳回',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let data = {
        id: formData.value.id,
        status: '20', // 默认20已驳回
        reviewLabel: '发布内容不符合迈从社区规范，请重新发布喔'
      }
      await ClubApi.auditDynamic(data)
      ElMessage({
        type: 'success',
        message: '驳回成功'
      })
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    })
    .catch(() => {})
}
const loading = ref(false)
/** 查询评论列表 */
const getCommentList = async () => {
  queryParams.dynamicId = formData.value.id
  loading.value = true
  try {
    const data = await ClubApi.getDynamicCommentList(queryParams)
    commentList.value = data.list
    totalComment.value = data.total
  } finally {
    loading.value = false
  }
}

// 话题列表
const topicList = ref([])
onMounted(async () => {
  const data = await topicApi.getTopicList({})
  topicList.value = data.list || []
})
</script>
